<template>
  <dtDialog
    :title="orgTextMap[orgDialogStatus]"
    :visible.sync="orgDialogFormVisible"
    :is-loading="loading"
    :footer-slot="orgDialogStatus === 'detail'? true : false"
    @closeDialog="orgResetTemp()"
    @comfirmBtn="onSubmit()"
  >
    <el-form
      ref="orgDataForm"
      slot="content"
      :rules="orgDialogStatus != 'detail'?orgRules:{}"
      :model="orgTemp"
      label-position="right"
      label-width="82px"
      :disabled="orgDialogStatus === 'detail'"
    >
      <el-form-item v-if="selectedorgFlag && orgTemp.orgParentId != -1" ref="orgParentIdRef" label="上级组织"
                    prop="orgParentId">
        <dt-select-person v-model.trim="orgTemp.orgParentId" :is-multiple="false" :select-type="'org'"
                          :select-data.sync="selectPerAndOrg" :is-disabled="orgDialogStatus === 'detail'" />
      </el-form-item>
      <el-form-item label="组织名称" prop="orgName">
        <el-input v-model.trim="orgTemp.orgName" maxlength="30" show-word-limit
                  class="limit" />
      </el-form-item>
      <el-form-item label="组织编码" prop="orgCode">
        <el-input v-model.trim="orgTemp.orgCode" :disabled="orgDialogStatus === 'update'" maxlength="30"
                  show-word-limit class="limit" />
      </el-form-item>
      <el-form-item label="组织层级" prop="orgLevel">
        <el-select v-model.trim="orgTemp.orgLevel" style="width:100%">
          <el-option
            v-for="dict in dict.type.orgLevel"
            :key="dict.value"
            :label="dict.label"
            :value="parseInt(dict.value)"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="部门类别" prop="orgCategory">
        <el-select v-model.trim="orgTemp.orgCategory" style="width:100%">
          <el-option
            v-for="dict in dict.type.orgType"
            :key="dict.value"
            :label="dict.label"
            :value="parseInt(dict.value)"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="排序" prop="orgSort">
        <el-input v-model.trim="orgTemp.orgSort" maxlength="8" :oninput="initPositiveInteger()"
                  show-word-limit class="limit" />
      </el-form-item>
      <el-form-item label="备注" prop="orgRemark">
        <el-input
          v-model.trim="orgTemp.orgRemark"
          maxlength="200"
          type="textarea"
          show-word-limit
          class="limit"
        />
      </el-form-item>
    </el-form>
  </dtDialog>
</template>
<script>
import hrOrganizationApi from '@/framework/api/userCenter/hrOrganization'
import { positiveInteger, checkSpecialStr, checkCode } from '@/framework/utils/validate'

export default {
  dicts: ['orgLevel', 'orgType'],
  data() {
    return {
      loading: false,
      orgDialogFormVisible: false,
      orgDialogStatus: '',
      selectedorgFlag: true,
      orgTextMap: {
        update: '修改组织',
        create: '新增组织',
        detail: '查看详情',
        createChildren: '新增下级组织'
      },
      orgTemp: {
        orgParentId: '',
        parentOrgName: '',
        orgName: '',
        orgCode: '',
        orgSort: '',
        orgRemark: '',
        orgLevel: '',
        orgCategory: ''
      },
      parentOrgName: '',
      oldParentOrgId: '',
      orgName: '',
      visible: false,
      tree: [],
      orgRules: {
        orgParentId: [{
          required: true,
          trigger: 'change',
          validator: (rule, value, callback) => {
            if (!value) {
              callback(new Error('请选择上级组织名称'))
            } else if (value === this.orgTemp.parentId) {
              callback(new Error('上级组织不可修改为当前组织'))
            } else {
              callback()
            }
          }
        }],
        orgName: [{
          required: true,
          trigger: 'change',
          validator: (rule, value, callback) => {
            if (!value) {
              callback(new Error('请输入组织名称'))
            } else if (!checkSpecialStr(value)) {
              callback(new Error('不要输入特殊字符'))
            } else {
              callback()
            }
          }
        }],
        orgCode: [{
          required: true,
          trigger: 'change',
          validator: (rule, value, callback) => {
            if (!value) {
              callback(new Error('请输入组织编码'))
            } else if (!checkCode(value)) {
              callback(new Error('请输入字母、数字或下划线'))
            } else {
              callback()
            }
          }
        }
        ],
        orgSort: [{
          required: false,
          message: '请输入组织顺序',
          trigger: 'blur'
        }
        ],
        orgRemark: [{
          required: false,
          validator: (rule, value, callback) => {
            if (!checkSpecialStr(value) && value) {
              callback(new Error('不要输入特殊字符'))
            } else callback()
          }
        }],
        orgLevel: [{
          required: true,
          trigger: 'change',
          message: '请选择组织层级'
        }],
        orgCategory: [{
          required: true,
          trigger: 'change',
          message: '请选择部门类别'
        }]
      },
      editUservisible: false,
      selectPerAndOrg: []

    }
  },
  methods: {
    // 获取组织树
    initTree() {
      const that = this
      hrOrganizationApi.fetchList().then((res) => {
        that.tree = res.data
      })
    },
    // 校验排序规则
    initPositiveInteger(data) {
      return positiveInteger(data)
    },
    // 关闭弹窗
    orgResetTemp() {
      this.orgTemp = {
        orgParentId: ''
      }
      this.parentOrgName = ''
      this.oldParentOrgId = ''
    },
    // 打开新增弹窗
    openOrg(row, type) {
      this.selectedorgFlag = true
      this.orgDialogFormVisible = true
      if (type == 'add') {
        this.orgDialogStatus = 'create'
      } else if (type == 'addChildren') {
        this.orgDialogStatus = 'create'
        this.orgTemp.orgParentId = row.orgId
        this.parentOrgName = row.orgName
        this.oldParentOrgId = row.orgId
      } else {
        if (type == 'update') {
          this.orgDialogStatus = 'update'
        } else {
          this.orgDialogStatus = 'detail'
        }
        hrOrganizationApi.detail(row.orgId).then((res) => {
          this.orgTemp = Object.assign({}, res.data)
          this.orgTemp.orgParentId = res.data.orgParentId
          this.parentOrgName = res.data.parentName
          this.oldParentOrgId = res.data.orgParentId
        })
      }
      this.$nextTick(() => {
        this.$refs['orgDataForm'].clearValidate()
      })
    },
    async onSubmit() {
      this.$refs['orgDataForm'].validate(async (valid) => {
        if (valid) {
          this.loading = true
          this.updateData()
        }
      })
    },
    async updateData() {
      const orgTempData = Object.assign({}, this.orgTemp)
      try {
        if (this.$parent.tableData[0].children && this.$parent.tableData[0].children.length == 0) {
          this.$set(this.$parent.tableData[0], 'hasChildren', true)
        }
        if (this.orgDialogStatus === 'create') {
          await hrOrganizationApi.add(orgTempData)
        } else {
          await hrOrganizationApi.edit(orgTempData)
        }
        // this.initTree()
        // todo 需要拿到打开编辑弹窗时的父组件数据  然后 更改 改变上级组织时需要同时处理两个组织
        let oldParentOrgId = ''
        if (orgTempData.orgParentId === this.oldParentOrgId) {
          oldParentOrgId = null
        } else {
          oldParentOrgId = this.oldParentOrgId
        }
        this.$parent.getList(orgTempData.orgParentId, oldParentOrgId)
        this.orgDialogFormVisible = false
        this.$dtMessage({
          message: this.orgDialogStatus == 'create' ? '新增成功' : '修改成功',
          type: 'success'
        })
        this.loading = false
      } catch (error) {
        this.loading = false
      }
    }
  }
}
</script>
<style>

</style>
